module ActsAsAspdotnet::ViewHelpers
  # add important tags into your <html><head>
  def aspdotnet_includes
    return [
      %(<meta name="vs_showGrid" content="False">),
      # the "Content" is capitalized to get a more authentic feel (try it on vs2003 for yourself)
      %(<meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">),
      %(<meta name="CODE_LANGUAGE" Content="C#">),
      # more fun meta tags
      %(<meta name="vs_defaultClientScript" content="JavaScript">),
      %(<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">),
      aspdotnet_js_includes
    ].join("\n")
  end
  
  def aspdotnet_js_includes
    unless @aspdotnet_js_includes_complete
      @aspdotnet_js_includes_complete = true
      
      # we need prototype becauase of the poorly written aspdotnet_validation js
      return [ 
        javascript_include_tag("prototype"),
        javascript_include_tag("aspdotnet_webforms"),
        javascript_include_tag("aspdotnet_validation")
      ].join("\n")
    end
  end
  
  # wrap form for to include our asp.net required javascript 
  def form_for(record_or_name_or_array, *args, &block)
    super(record_or_name_or_array, args, &block)
    
    # yes, i know. i'm brilliant
    concat(page_validators, block.binding)  
  end 
  
  # override Rails form_tag_html to include our super fancy tags
  def form_tag_html(html_options)
    [
      aspdotnet_js_includes,
      super(html_options), 
      event_input_tags,
      viewstate_tag,
      do_post_back(html_options)
    ].join("\n")
  end
  
  # returns a populated viewstate tag
  def viewstate_tag(data = {})
    hidden_field_tag("__VIEWSTATE", generate_viewstate(data))
  end

  # generates a random string use extremely useful viewstate information
  def generate_viewstate(data = {}, size = 1000)
    char_list = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a + ["+","/","-"]
    viewstate = ""
    1.upto(size) { |i| viewstate << char_list[rand(char_list.size-1)] }
    return "/"+viewstate+"="
  end
  
  # some fantastic little event tags that make our web form sparkle
  def event_input_tags
    [
      hidden_field_tag("__EVENTTARGET", "", :id => "__EVENTTARGET"),
      hidden_field_tag("__EVENTARGUMENT", "", :id => "__EVENTARGUMENT")
    ].join("\n")
  end
  
  # Return our wonderful little client element id
  def client_id(orig_id)
    ActionView::Helpers::InstanceTag.get_client_id(orig_id.to_s)
  end
  
  
end
